//
//  ShopSetViewController.m
//  ForestPack
//
//  Created by 郑洲 on 2018/7/9.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "ShopSetViewController.h"
#import <AFNetworking.h>

@interface ShopSetViewController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UITextViewDelegate>

@property (nonatomic, assign) BOOL isEdit;
@property (nonatomic, strong) BaseTableView *tableView;

@property (nonatomic, strong) NSMutableArray *tagArr;
@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, copy)   NSString *currentTag;
@end

@implementation ShopSetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"店铺管理";
    _isEdit = NO;
    _currentTag = @"";
    [self setRightButton:nil title:@"修改" target:self action:@selector(edit:)];
    self.tagArr = [NSMutableArray array];
    
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    
    for (NSDictionary *dic in _shopInfo.labels) {
        [self.tagArr addObject:dic[@"name"]];
    }
}

- (void)edit:(UIButton *)button {
    if (!_isEdit) {
        [button setTitle:@"保存" forState:UIControlStateNormal];
        _isEdit = !_isEdit;
        [_tableView reloadData];
    }else {
        [button setTitle:@"修改" forState:UIControlStateNormal];
        [self updata];
    }
}

- (void)updata {
    [self.view endEditing:YES];
    NSString *tag = @"";
    for (NSString *str in _tagArr) {
        tag = [tag stringByAppendingString:[NSString stringWithFormat:@",%@",str]];
    }
    if (tag.length > 0) {
        tag = [tag substringFromIndex:1];
    }
    [HttpManager showWait];
    NSData *imageData = [NSData data];
    if (_imageView.image) {
        imageData = UIImageJPEGRepresentation(_imageView.image, kUploadImageCompressionRatio);
    }
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html",nil,nil];
    // 将本地的文件上传至服务器
    NSString *urlStr = [NSString stringWithFormat:@"%@app/ajax_file_upload",REQUESTHEADER];
    [manager POST:urlStr parameters:@{@"files[]":@[imageData]} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:@"files[]" fileName:@"shopHead.jpg" mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([responseObject[@"status"] integerValue] == 1) {
            NSString *picUrl = [NSString stringWithFormat:@"%@",responseObject[@"pic"][0]];
            
            NSString *url = [NSString stringWithFormat:@"%@app/shop_update",REQUESTHEADER];
            NSDictionary *parameter = @{@"logo":picUrl,@"token":[FPLoginAndRegisterTools getToken],@"shop_id":self.shopInfo.Id,@"label":tag,@"name":self.shopInfo.name,@"address":self.shopInfo.address,@"intro":self.shopInfo.intro};
            [HttpManager postHttpRequestByPost:url andParameter:parameter success:^(id successResponse) {
                NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
                if ([status isEqualToString:@"1"]) {
                    [HttpManager hideWait];
                    [HttpManager showNoteMsg:@"资料更新成功"];
                    self.isEdit = !self.isEdit;
                    [self.tableView reloadData];

                    NSNotification *notification = [[NSNotification alloc]initWithName:@"ReloadShop" object:nil userInfo:nil];
                    [[NSNotificationCenter defaultCenter] postNotification:notification];
                }else{
                    [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
                }
            } andFailure:^(id failureResponse) {
                [HttpManager showFail];
            }];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //        NSLog(@"错误 %@", error.localizedDescription);
        [HttpManager hideWait];
        [HttpManager showNoteMsg:@"上传失败"];
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 3;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *cellId = @"setCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        for (UIView *view in cell.subviews) {
            [view removeFromSuperview];
        }
        NSArray *noteArr = @[@"店铺头像",@"店铺名称",@"店铺地址"];
        UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), 0, ScreenX375(60), ScreenX375(45))];
        noteLabel.text = noteArr[indexPath.row];
        noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
        noteLabel.font = Kfont(14);
        [cell addSubview:noteLabel];
        
        if (indexPath.row == 0) {
            if (!_imageView) {
                _imageView = [[UIImageView alloc] init];
                [_imageView sd_setImageWithURL:[NSURL URLWithString:_shopInfo.logo] placeholderImage:nil options:SDWebImageRetryFailed];
                _imageView.layer.cornerRadius = ScreenX375(16.5);
                _imageView.clipsToBounds = YES;
            }
            [cell addSubview:_imageView];
            if (_isEdit) {
                _imageView.frame = CGRectMake(SCREEN_WIDTH - ScreenX375(62), ScreenX375(6), ScreenX375(33), ScreenX375(33));
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }else {
                _imageView.frame = CGRectMake(SCREEN_WIDTH - ScreenX375(45), ScreenX375(6), ScreenX375(33), ScreenX375(33));
                cell.accessoryType = UITableViewCellAccessoryNone;
            }
        }else if (indexPath.row == 1) {
            if (_isEdit) {
                UITextField *nameFiled = [[UITextField alloc] initWithFrame:CGRectMake(ScreenX375(89), 0, ScreenX375(250), ScreenX375(45))];
                nameFiled.textColor = REXADECIMALCOLOR(@"#999999");
                nameFiled.font = Kfont(14);
                nameFiled.text = _shopInfo.name;
                nameFiled.tag = 100;
                nameFiled.delegate = self;
                nameFiled.returnKeyType = UIReturnKeyDone;
                [cell addSubview:nameFiled];
            }else {
                UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - ScreenX375(213), 0, ScreenX375(200), ScreenX375(45))];
                nameLabel.textColor = REXADECIMALCOLOR(@"#999999");
                nameLabel.font = Kfont(14);
                nameLabel.textAlignment = NSTextAlignmentRight;
                nameLabel.text = _shopInfo.name;
                [cell addSubview:nameLabel];
            }
            UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(13), 0, SCREEN_WIDTH - ScreenX375(26), 0.5)];
            line.image = [UIImage imageNamed:@"虚线"];
            [cell addSubview:line];
        }else {
            if (_isEdit) {
                UITextField *adddressFiled = [[UITextField alloc] initWithFrame:CGRectMake(ScreenX375(89), 0, ScreenX375(250), ScreenX375(45))];
                adddressFiled.textColor = REXADECIMALCOLOR(@"#999999");
                adddressFiled.font = Kfont(14);
                adddressFiled.text = _shopInfo.address;
                adddressFiled.tag = 101;
                adddressFiled.delegate = self;
                adddressFiled.returnKeyType = UIReturnKeyDone;
                [cell addSubview:adddressFiled];
                
//                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }else {
                UILabel *addressLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - ScreenX375(263), 0, ScreenX375(250), ScreenX375(45))];
                addressLabel.textColor = REXADECIMALCOLOR(@"#999999");
                addressLabel.font = Kfont(14);
                addressLabel.textAlignment = NSTextAlignmentRight;
                addressLabel.text = _shopInfo.address;
                [cell addSubview:addressLabel];
                
//                cell.accessoryType = UITableViewCellAccessoryNone;
            }
            UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(13), 0, SCREEN_WIDTH - ScreenX375(26), 0.5)];
            line.image = [UIImage imageNamed:@"虚线"];
            [cell addSubview:line];
        }
        
        return cell;
    }else if (indexPath.section == 2) {
        static NSString *cellId = @"detailCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        for (UIView *view in cell.subviews) {
            [view removeFromSuperview];
        }
        if (_isEdit) {
            UITextView *detailView = [[UITextView alloc] initWithFrame:CGRectMake(ScreenX375(13), 0, SCREEN_WIDTH - ScreenX375(26), ScreenX375(112))];
            detailView.textColor = REXADECIMALCOLOR(@"#999999");
            detailView.font = Kfont(14);
            detailView.layer.cornerRadius = 5;
            detailView.clipsToBounds = YES;
            detailView.layer.borderWidth = 1;
            detailView.layer.borderColor = REXADECIMALCOLOR(@"#dcdcdc").CGColor;
            detailView.delegate = self;
            detailView.returnKeyType = UIReturnKeyDone;
            if (_shopInfo.intro.length > 0) {
                detailView.text = _shopInfo.intro;
            }else {
                detailView.text = @"雇主未作出评价，系统默认好评雇主未作出评价，系统默认好评雇主未作出评价，系统默认好评雇主未作出评价，系统默认好评";
            }
            [cell addSubview:detailView];
        }else {
            UILabel *detailLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(1), SCREEN_WIDTH - ScreenX375(26), ScreenX375(70))];
            detailLabel.textColor = REXADECIMALCOLOR(@"#999999");
            detailLabel.font = Kfont(14);
            detailLabel.numberOfLines = 0;
            if (_shopInfo.intro.length > 0) {
                detailLabel.text = _shopInfo.intro;
            }else {
                detailLabel.text = @"雇主未作出评价，系统默认好评雇主未作出评价，系统默认好评雇主未作出评价，系统默认好评雇主未作出评价，系统默认好评";
            }
            [cell addSubview:detailLabel];
        }
        
        return cell;
    }else {
        static NSString *cellId = @"tagCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        for (UIView *view in cell.subviews) {
            [view removeFromSuperview];
        }
        if (!_isEdit) {
            for (int i = 0; i < _tagArr.count; i++) {
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13) + i % 3 * ScreenX375(104), ScreenX375(15) + i / 3 * ScreenX375(45), ScreenX375(94), ScreenX375(30))];
                label.backgroundColor = ThemeColor;
                label.layer.cornerRadius = ScreenX375(15);
                label.clipsToBounds = YES;
                label.text = _tagArr[i];
                label.textAlignment = NSTextAlignmentCenter;
                label.font = Kfont(14);
                label.textColor = [UIColor whiteColor];
                [cell addSubview:label];
            }
        }else {
            for (int i = 0; i < _tagArr.count + 1; i++) {
                UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(13) + i % 3 * ScreenX375(104), ScreenX375(15) + i / 3 * ScreenX375(45), ScreenX375(94), ScreenX375(30))];
                button.backgroundColor = ThemeColor;
                button.layer.cornerRadius = ScreenX375(15);
                button.clipsToBounds = YES;
                button.tag = 200 + i;
                if (i < _tagArr.count) {
                    [button setTitle:_tagArr[i] forState:UIControlStateNormal];
                    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(btnLong:)];
                    longPress.minimumPressDuration = 0.5; //定义按的时间
                    [button addGestureRecognizer:longPress];
                }else {
                    [button setImage:[UIImage imageNamed:@"+副本"] forState:UIControlStateNormal];
                    [button addTarget:self action:@selector(addTag) forControlEvents:UIControlEventTouchUpInside];
                }
                button.titleLabel.font = Kfont(14);
                [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                [cell addSubview:button];
            }
        }
        return cell;
    }
}

-(void)btnLong:(UILongPressGestureRecognizer *)gestureRecognizer{
     if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
         UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"是否确认删除标签" message:nil preferredStyle:UIAlertControllerStyleAlert];
         
         UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
         UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
             [self.tagArr removeObjectAtIndex:gestureRecognizer.view.tag - 200];
             [self.tableView reloadSections:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, 1)] withRowAnimation:UITableViewRowAnimationNone];
         }];
         
         [alertController addAction:cancel];
         [alertController addAction:sure];
         
         [self presentViewController:alertController animated:YES completion:nil];
     }
}

- (void)addTag {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请输入标签名称" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        [textField addTarget:self action:@selector(textFieldChange:) forControlEvents:UIControlEventEditingChanged];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (self.currentTag.length == 0) {
            [HttpManager showNoteMsg:@"请输入标签名称"];
            return ;
        }
        [self.tagArr addObject:self.currentTag];
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, 1)] withRowAnimation:UITableViewRowAnimationNone];
    }];
    
    [alertController addAction:cancel];
    [alertController addAction:sure];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)textFieldChange:(UITextField *)textField {
    self.currentTag = textField.text;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 0 && _isEdit) {
        UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择", nil];
        actionSheet.tag = 1;
        [actionSheet showFromTabBar:self.tabBarController.tabBar];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return ScreenX375(45);
    }else if (indexPath.section == 2) {
        return ScreenX375(112);
    }
    if (_isEdit) {
        return ScreenX375(15) + (_tagArr.count / 3 + 1) * ScreenX375(45);
    }else {
        return ScreenX375(15) + ((_tagArr.count > 0 ? (_tagArr.count - 1): 0) / 3 + 1) * ScreenX375(45);
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return ScreenX375(53);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section != 2) {
        return ScreenX375(10);
    }
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(53))];
    view.backgroundColor = [UIColor whiteColor];
    
    UIView *rline = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenX375(15), ScreenX375(3), ScreenX375(23))];
    rline.backgroundColor = ThemeColor;
    [view addSubview:rline];
    
    UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(15), ScreenX375(200), ScreenX375(24))];
    noteLabel.text = section == 0 ? @"店铺信息" : (section == 1 ? @"店铺标签" : @"店铺描述");
    noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
    noteLabel.font = Kfont(18);
    [view addSubview:noteLabel];
    
    if (!(section == 2 && _isEdit)) {
        UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(0, ScreenX375(53) - 0.5, SCREEN_WIDTH, 0.5)];
        line.backgroundColor = LineColor;
        [view addSubview:line];
    }
    
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section != 2) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(10))];
        view.backgroundColor = TABLEVIEW_BACKGROUNDCOLOR;
        return view;
    }
    return nil;
}

#pragma mark - UIActionSheet Delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (actionSheet.tag == 1){
        NSUInteger sourceType = 0;
        //判断是否支持照相机
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc]init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        switch (buttonIndex) {
            case 0:
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                    //拍照
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    // 跳转到相机
                    imagePickerController.sourceType = sourceType;
                    [self presentViewController:imagePickerController animated:YES completion:nil];
                }
                break;
            case 1:
                //从相册中取
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                //跳转到相册
                imagePickerController.sourceType = sourceType;
                [self presentViewController:imagePickerController animated:YES completion:nil];
                break;
            default:
                break;
        }
        
    }
}

#pragma mark - UIImagePickerControllerDelegate  图片处理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    NSLog(@"Picker returned successfully.");
    //    将选择的图片在imageView上显示
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    _imageView.image = image;
    //处理完毕，回到个人信息页面
    [picker dismissViewControllerAnimated:YES completion:nil];
    //    [_tableView reloadData];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    NSLog(@"Picker was cancelled");
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:YES];
    return NO;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField.tag == 100) {
        _shopInfo.name = textField.text;
    }else if (textField.tag == 101) {
        _shopInfo.address = textField.text;
    }
}

- (void)textViewDidBeginEditing:(UITextView *)textView {
    [UIView animateWithDuration:0.3 animations:^{
        self.tableView.frame = CGRectMake(0, -ScreenX375(200), SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT);
    }];
    if ([textView.text isEqualToString:@"雇主未作出评价，系统默认好评雇主未作出评价，系统默认好评雇主未作出评价，系统默认好评雇主未作出评价，系统默认好评"]) {
        textView.text = @"";
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    [UIView animateWithDuration:0.3 animations:^{
        self.tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT);
    }];
    _shopInfo.intro = textView.text;
    if (textView.text.length == 0) {
        textView.text = @"雇主未作出评价，系统默认好评雇主未作出评价，系统默认好评雇主未作出评价，系统默认好评雇主未作出评价，系统默认好评";
    }
}

@end
